package com.south.base.test.arithmetic;

import java.util.Arrays;

/**
 * 寻找两个有序数组的中位数
 *
 * @author Administrator
 * @date 2019/5/24 15:53
 */
public class MedianSortedArrays {
    public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int len = nums1.length + nums2.length;
        int medianLen1 = len / 2 + len % 2;
        int medianLen2 = len / 2 + len % 2;
        if (len % 2 == 0) {
            medianLen2 += 1;
        }
        int median1, median2;
        if (nums2.length == 0) {
            median1 = nums1[medianLen1 - 1];
            median2 = nums1[medianLen2 - 1];
        } else if (nums1.length == 0) {
            median1 = nums2[medianLen1 - 1];
            median2 = nums2[medianLen2 - 1];
        } else if (nums1[nums1.length - 1] <= nums2[0]) {
            median1 = medianLen1 > nums1.length ? nums2[medianLen1 - 1 - nums1.length] : nums1[medianLen1 - 1];
            median2 = medianLen2 > nums1.length ? nums2[medianLen2 - 1 - nums1.length] : nums1[medianLen2 - 1];
        } else if (nums1[0] >= nums2[nums2.length - 1]) {
            median1 = medianLen1 > nums2.length ? nums1[medianLen1 - 1 - nums2.length] : nums2[medianLen1 - 1];
            median2 = medianLen2 > nums2.length ? nums1[medianLen2 - 1 - nums2.length] : nums2[medianLen2 - 1];
        } else {
            int[] nums = new int[len];
            System.arraycopy(nums1, 0, nums, 0, nums1.length);
            System.arraycopy(nums2, 0, nums, nums1.length, nums2.length);
            Arrays.sort(nums);
            median1 = nums[medianLen1 - 1];
            median2 = nums[medianLen2 - 1];
        }

        return (len % 2 != 0) ? (double) ((median1 + median2) / 2) : ((double)median1 + (double)median2) / 2;
    }

    public static void main(String[] args) {
//        System.out.println(findMedianSortedArrays(new int[]{}, new int[]{1}));
//        System.out.println(findMedianSortedArrays(new int[]{}, new int[]{1,2}));
//        System.out.println(findMedianSortedArrays(new int[]{}, new int[]{1,2,3}));
        System.out.println(findMedianSortedArrays(new int[]{2}, new int[]{1,3}));
//        System.out.println(findMedianSortedArrays(new int[]{}, new int[]{1,2,3,6}));
//        System.out.println(findMedianSortedArrays(new int[]{}, new int[]{1,2,2,6}));
    }
}
